package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.task.ITaskClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutomaticReviewService;
import com.heima.wemedia.service.WmNewsTaskService;
import javafx.scene.control.TableColumn;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/17 18:22
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
  @Autowired private ITaskClient iTaskClient;
  @Autowired private WmNewsAutomaticReviewService automaticReviewService;

  /**
   * 添加定时任务
   *
   * @param id
   * @param publishTime
   */
  @Override
  @Async
  public void addNewsToTask(Integer id, Date publishTime) {
    log.info("添加任务到延迟服务中----begin");

    Task task = new Task();
    task.setExecuteTime(publishTime.getTime());
    task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
    task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
    WmNews wmNews = new WmNews();
    wmNews.setId(id);
    task.setParameters(ProtostuffUtil.serialize(wmNews));

    iTaskClient.addTask(task);

    log.info("添加任务到延迟服务中----end");
  }

  /** 消费定时任务 */
  @Override
  @Scheduled(fixedRate = 50000)
  @SneakyThrows
  public void pollNewsTask() {
    log.info("文章审核---消费任务执行---begin---");
    // 远程调用，修改数据库、修改redis
    ResponseResult result =
        iTaskClient.pollTask(
            TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
    if (result.getCode() == 200 && result.getData() != null) {
      // 从返回值中获取data
      Object data = result.getData();
      String jsonStr = JSON.toJSONString(data);
      Task task = JSON.parseObject(jsonStr, Task.class);
      byte[] parameters = task.getParameters();
      WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
      // 自动审核
      automaticReviewService.newsAutomaticReview(wmNews.getId());
    }
    log.info("文章审核---消费任务执行---end---");
  }
}
